/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/render', 'N/file', 'N/runtime', '../common/moment', 'N/search'], function (record, render, file, runtime, moment, search) {
    function beforeLoad(context) {
        if (context.type === 'view') {
            try {
                var soRecord = record.load({
                    type: record.Type.SALES_ORDER,
                    id: context.newRecord.id,
                    isDynamic: true
                });
                /*                for (var i = 0; i < JSON.stringify(soRecord).length; i = i + 3000) {
                                    log.debug({
                                        title: 'JSON.stringify(soRecord)' + i,
                                        details: JSON.stringify(soRecord).slice(i, i + 3000)
                                    });
                                }*/


                var label = {};
                label.internalid = soRecord.getValue('id');
                //订单号
                label.tranid = soRecord.getValue('tranid');
                //订单日期
                var trandateTime = soRecord.getValue('trandate').getTime();
                var trandateDate = new Date(trandateTime);
                label.trandate_year = trandateDate.getFullYear();
                label.trandate_month = trandateDate.getMonth() + 1;
                label.trandate_date = trandateDate.getDate();
                //采购单位
                label.customer = soRecord.getText('entity');
                //销售单位
                label.subsidiaryText = soRecord.getText('subsidiary');
                //子公司
                label.subsidiary = soRecord.getValue('subsidiary');
                var subsidiaryRecord = record.load({
                    type: record.Type.SUBSIDIARY,
                    id: label.subsidiary
                });
                //本位币-货币
                label.currency_bwb = subsidiaryRecord.getValue('currency');
                //采购订单
                label.otherrefnum = soRecord.getValue('otherrefnum');
                //销售渠道
                label.custbody_saleschannels = soRecord.getValue('custbody_saleschannels');
                //币种
                label.currency = soRecord.getText('currency');
                //汇率
                label.exchangerate = soRecord.getValue('exchangerate');
                //付运地址
                label.shipaddress = soRecord.getValue('shipaddress');
                //发运方式
                label.shipmethod = soRecord.getText('shipmethod');
                //业务员-销售代表
                label.salesrep = soRecord.getText('salesrep');
                //联系方式
                label.contact = soRecord.getValue('custbody_contact');
                //备注
                label.memo = soRecord.getValue('memo');
                //订单数量总计
                var total_quantity = 0;
                //未税单价总计
                var total_rate = 0;
                //未税金额总计-原币
                var total_amount_yb = 0;
                //含税金额总计-原币
                var total_grossamount_yb = 0;
                var itemLinesNum = soRecord.getLineCount({
                    sublistId: 'item'
                });
                if (itemLinesNum === -1) {
                    return;
                }
                label.itemList = [];
                //遍历item sublist
                for (var i = 0; i < itemLinesNum; i++) {
                    var item = {};
                    //序号
                    item.no = i + 1;
                    //国家
                    item.journal_country = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_journal_country',
                        line: i
                    });
                    //交货日期
                    var delivery_date = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_delivery_date',
                        line: i
                    });
                    if (delivery_date !== undefined && delivery_date !== "") {
                        var dateFormat = runtime.getCurrentUser().getPreference('DATEFORMAT');
                        item.delivery_date = moment(delivery_date, dateFormat).format('YYYY/MM/DD');
                    }
                    //中文名称
                    item.chinese_name = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_chinese_name',
                        line: i
                    });
                    //尺寸（规格）
                    item.specification = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_specification',
                        line: i
                    });
                    //色号
                    item.colornumber = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_colornumber',
                        line: i
                    });
                    //颜色
                    item.color = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_color',
                        line: i
                    });
                    //花型
                    item.flower_type = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_flower_type',
                        line: i
                    });
                    //花型色
                    item.flower_type_color = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_flower_type_color',
                        line: i
                    });
                    //单位
                    item.units = soRecord.getSublistText({
                        sublistId: 'item',
                        fieldId: 'units',
                        line: i
                    });
                    //订单数量
                    item.quantity = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity',
                        line: i
                    });
                    total_quantity = Number(total_quantity) + Number(item.quantity);
                    //未税单价
                    item.rate = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'rate',
                        line: i
                    });
                    total_rate = Number(total_rate) + Number(item.rate);
                    //未税金额
                    item.amount = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'amount',
                        line: i
                    });
                    total_amount_yb = Number(total_amount_yb) + Number(item.amount);
                    //含税金额 taxdetails
                    item.grossamount = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'grossamt',
                        line: i
                    });
                    log.debug("item.grossamount", item.grossamount);
                    total_grossamount_yb = Number(total_grossamount_yb) + Number(item.grossamount);
                    //交易方式
                    item.trade_pay_method = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_trade_pay_method',
                        line: i
                    });
                    //价格
                    item.trade_price = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_trade_price',
                        line: i
                    });
                    //备注
                    item.remarks = soRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_remarks',
                        line: i
                    });
                    var itemId = soRecord.getSublistValue({sublistId: 'item', fieldId: 'item', line: i});
                    var mySearch = search.create({
                        type: search.Type.INVENTORY_ITEM,
                        filters: ['internalid', 'is', itemId],
                        columns: ['itemid', 'custitem_door_width']
                    });
                    var searchResult = mySearch.run().getRange({start: 0, end: 1});
                    if (searchResult.length > 0) {
                        //log.debug('searchResult', searchResult);
                        //产品名称编码
                        item.itemid = searchResult[0].getValue('itemid');
                        //尺寸（规格）
                        item.specification = searchResult[0].getValue('custitem_door_width');
                    } else {
                        var itemRecord = record.load({
                            type: search.Type.ASSEMBLY_ITEM,
                            id: itemId,
                            isDynamic: false
                        });
                        //产品名称编码
                        item.itemid = itemRecord.getValue('itemid');
                        item.sku = itemRecord.getValue('custitem_child_sku');
                    }
                    label.itemList.push(item);
                }
                label.total_quantity = total_quantity;
                label.total_rate = total_rate;
                label.total_amount_yb = total_amount_yb;
                label.total_grossamount_yb = total_grossamount_yb;
                label.total_tax_yb = Number(total_grossamount_yb) - Number(total_amount_yb);
                label.total_amount_bwb = Number(total_amount_yb) * Number(label.exchangerate);
                label.total_grossamount_bwb = Number(total_grossamount_yb) * Number(label.exchangerate);
                label.total_tax_bwb = Number(label.total_tax_yb) * Number(label.exchangerate);
                log.debug("lable", label);
                //调用模板文件
                var renderer = render.create();
                renderer.templateContent = file.load(1164).getContents();
                renderer.addCustomDataSource({
                    format: render.DataSource.JSON,
                    alias: 'label',
                    data: JSON.stringify(label)
                });
                var pdfFile = renderer.renderAsPdf();
                //PDF文件存放文件夹ID
                pdfFile.folder = 185;
                pdfFile.name = 'SO' + label.internalid + '-' + new Date().getTime() + '.pdf';
                var fileId = pdfFile.save();
                var File = file.load(fileId);
                var pdfurl = File.url;
                var form = context.form;
                form.addButton({
                    id: 'custpage_button',
                    label: '打印销售单',
                    functionName: "window.open('" + pdfurl + "');"
                });
            } catch (e) {
                log.error(e.name, e.message);
            }

        }
    }


    return {
        beforeLoad: beforeLoad
    };
});
